package com.legal.controller.chat;

import cn.hutool.core.bean.BeanUtil;

import com.legal.domain.dto.CaseChatDTO;
import com.legal.domain.po.ChatMemoryMsg;
import com.legal.domain.result.Result;
import com.legal.service.chat.AnalysisChatService;
import com.legal.service.chat.ICasesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.io.IOException;

@RequestMapping("/ai/analysis")
@RestController
@RequiredArgsConstructor
@Tag(name = "案件分析对话接口")  // OpenAPI 3.0 注解
@Slf4j
public class AnalysisChatController {

    private final AnalysisChatService analysisChatService;
    private final ICasesService casesService;


    /**
     * 案件分析chat聊天
     *
     * @param caseChatDTO 案件对话用户端传来的实体
     * @return
     */
    @Operation(summary = "案件分析")
    @PostMapping(value = "/chat", produces = "text/html;charset=utf-8")
    public Flux<String> chatStream(@RequestBody CaseChatDTO caseChatDTO) {
        //判断是不是第一次对话，如果是第一次对话，则添加案件chatId
        if(caseChatDTO.getId()!= null){
            log.info("第一次对话id{}", caseChatDTO.getId());
            casesService.addChatId(caseChatDTO.getChatId(), caseChatDTO.getId());
        }
        //属性拷贝
        ChatMemoryMsg chatMemoryMsg = BeanUtil.copyProperties(caseChatDTO, ChatMemoryMsg.class);
        log.info("案件分析:{}", chatMemoryMsg);
        return analysisChatService.chat(chatMemoryMsg);
    }

    /**
     * @param id   案件的id
     * @param file 文件
     *             文件上传,
     */
    @Operation(summary = "案件分析文件上传")
    @PostMapping("/upload")
    public Result<Void> uploadPdf(
            @RequestParam("id") Integer id,
            @RequestParam("file") MultipartFile file) {
        analysisChatService.save(id, file);
        return Result.ok();
    }


    /**
     * 文件下载
     */
    @Operation(summary = "案件分析文件下载")
    @GetMapping("/file/{chatId}")
    public ResponseEntity<Resource> download(@PathVariable("chatId") String chatId) throws IOException {
        return analysisChatService.download(chatId);
    }


}
